<script setup lang="ts">
import { onMounted, ref } from "vue";
import { showToast } from "vant";
import { http } from "@/utils/http";
import { useLocationParams } from "@/store/useLocationStore";
import { DealerInfo } from "@/typings/dealer";
import { useUserStore } from "@/store/useUserStore";
import { useAuthStore } from "@/store/useAuthStore";
import { useRoute } from "vue-router";
const loading = ref(false);
const isRegistered = ref(false);
const showRegisteredDialog = ref(false);
const showSuccessDialog = ref(false);
const { getAllParams } = useLocationParams();
const { ic, ...otherParams } = getAllParams();
const dealerInfo = ref<DealerInfo | null>(null);
const errorData = ref<ErrorData>(null);
const name = ref("");
const phone = ref("");
const showInputDialog = ref(false);

interface ErrorData {
  您的信息: string;
  您所属团长: string;
  当前链接团长: string;
  注册日期: string;
  团长审核状态?: string;
}
const route = useRoute();
const authStore = useAuthStore();
const register = async code => {
  try {
    const data = await http.request({
      url: "/login/register",
      method: "POST",
      headers: { "No-Auth": true },
      data: { ...otherParams, code, name: name.value, phone: phone.value }
    });
    return data;
  } catch (error) {
    if (error.errorData) {
      errorData.value = error.errorData;
      showRegisteredDialog.value = true;
    }
  }
};
const getDealerInfo = async () => {
  try {
    loading.value = true;
    const data = await http.request<DealerInfo>({
      url: "/login/getDealerInfo",
      method: "POST",
      headers: { "No-Auth": true },
      data: {
        ...otherParams
      }
    });
    if (data) {
      dealerInfo.value = data;
    }
  } catch (error) {
    showToast("获取信息失败");
  } finally {
    loading.value = false;
  }
};

onMounted(() => {
  getDealerInfo();
});

const handleJoin = async () => {
  const { removeParam, getParam } = useLocationParams();
  const code = getParam("code");
  if (!code) {
    authStore.handleAuth(route);
    return;
  }
  if (ic?.toString() === "1") {
    if (!name.value || !phone.value) {
      showToast("请填写完整信息");
      return;
    }
    if (!validatePhone(phone.value)) {
      showToast("请输入正确的手机号");
      return;
    }
  }
  try {
    removeParam("code");
    loading.value = true;
    const data: any = await register(code);
    if (!data) {
      return;
    }
    showSuccessDialog.value = true;
    isRegistered.value = true;
  } catch (error) {
    console.log(error);
  } finally {
    loading.value = false;
  }
};

const handleInputSubmit = () => {
  if (!name.value || !phone.value) {
    showToast("请填写完整信息");
    return;
  }
  showInputDialog.value = false;
  handleJoin();
};

const validatePhone = (val: string) => {
  const phoneReg = /^1[3-9]\d{9}$/;
  return phoneReg.test(val);
};
</script>

<template>
  <div
    class="min-h-screen bg-gradient-to-b from-blue-50 to-white flex flex-col items-center px-6 pt-16 relative overflow-hidden"
  >
    <!-- Loading Overlay -->
    <van-overlay :show="loading" class="flex items-center justify-center">
      <van-loading type="spinner" color="#3b82f6" size="36px" />
    </van-overlay>

    <!-- 背景装饰 -->
    <div class="absolute inset-0 overflow-hidden pointer-events-none">
      <!-- 左上角装饰 -->
      <div
        class="absolute -left-16 -top-16 w-48 h-48 bg-blue-200 rounded-full opacity-10 blur-3xl"
      ></div>
      <!-- 右上角装饰 -->
      <div
        class="absolute -right-16 top-32 w-64 h-64 bg-blue-300 rounded-full opacity-10 blur-3xl"
      ></div>
      <!-- 底部装饰 -->
      <div
        class="absolute -bottom-8 left-1/2 -translate-x-1/2 w-96 h-32 bg-blue-100 rounded-full opacity-30 blur-2xl"
      ></div>
      <!-- 波浪纹理 -->
      <div class="absolute inset-0 opacity-5">
        <svg xmlns="http://www.w3.org/2000/svg" width="100%" height="100%">
          <defs>
            <pattern
              id="wave"
              width="100"
              height="100"
              patternUnits="userSpaceOnUse"
            >
              <path
                d="M0 50 Q 25 25, 50 50 T 100 50"
                stroke="currentColor"
                fill="none"
                stroke-width="2"
              />
            </pattern>
          </defs>
          <rect width="100%" height="100%" fill="url(#wave)" />
        </svg>
      </div>
    </div>

    <!-- 头像和标题容器 -->
    <div class="w-full max-w-md mb-12">
      <div class="flex items-center justify-center space-x-2 mb-2">
        <div class="w-6 h-6">
          <svg
            xmlns="http://www.w3.org/2000/svg"
            viewBox="0 0 24 24"
            fill="currentColor"
            class="text-blue-400"
          >
            <path
              fill-rule="evenodd"
              d="M7.5 6a4.5 4.5 0 119 0 4.5 4.5 0 01-9 0zM3.751 20.105a8.25 8.25 0 0116.498 0 .75.75 0 01-.437.695A18.683 18.683 0 0112 22.5c-2.786 0-5.433-.608-7.812-1.7a.75.75 0 01-.437-.695z"
              clip-rule="evenodd"
            />
          </svg>
        </div>
        <h1 class="text-xl text-blue-400">邀请您成为会员</h1>
      </div>
    </div>

    <!-- 用户名容器 -->
    <div class="w-2/3 max-w-md mb-8">
      <div class="bg-white/80 backdrop-blur-sm rounded-2xl px-6 py-5 shadow-md">
        <h2 class="text-gray-700 text-xl font-medium text-center">
          {{ dealerInfo?.name || "" }}
        </h2>
      </div>
    </div>

    <!-- 输入信息容器 -->
    <div v-if="ic?.toString() === '1'" class="w-2/3 max-w-md mb-8">
      <div
        class="bg-white/80 backdrop-blur-sm rounded-2xl px-6 py-4 shadow-md space-y-4"
      >
        <van-field
          v-model="name"
          label=""
          placeholder="请输入"
          class="!p-0"
          :rules="[{ required: true, message: '请输入' }]"
        />
        <van-field
          v-model="phone"
          label=""
          placeholder="请输入"
          class="!p-0"
          :rules="[
            { required: true, message: '请输入' },
            { validator: validatePhone }
          ]"
        />
      </div>
    </div>

    <!-- 申请按钮容器 -->
    <div class="w-full max-w-md px-0 mt-auto mb-12">
      <button
        @click="handleJoin()"
        :disabled="loading || isRegistered"
        class="w-full py-3.5 rounded-full bg-gradient-to-r from-blue-400 to-blue-500 text-white text-lg font-medium active:opacity-90 transition-all duration-300 shadow-lg shadow-blue-300/30 hover:shadow-blue-300/50 hover:scale-[1.02] disabled:opacity-50 disabled:cursor-not-allowed"
      >
        <template v-if="loading">
          <van-loading type="spinner" color="#ffffff" size="20px" />
        </template>
        <template v-else> 申请加入 </template>
      </button>
    </div>

    <!-- 已注册提示弹窗 -->
    <van-dialog
      v-model:show="showRegisteredDialog"
      :showConfirmButton="true"
      confirmButtonText="知道了"
      class="register-dialog"
    >
      <div class="p-6">
        <div class="flex justify-center mb-4">
          <div
            class="w-12 h-12 rounded-full bg-blue-50 flex items-center justify-center"
          >
            <svg
              xmlns="http://www.w3.org/2000/svg"
              viewBox="0 0 24 24"
              fill="currentColor"
              class="w-6 h-6 text-blue-400"
            >
              <path
                fill-rule="evenodd"
                d="M2.25 12c0-5.385 4.365-9.75 9.75-9.75s9.75 4.365 9.75 9.75-4.365 9.75-9.75 9.75S2.25 17.385 2.25 12zm8.706-1.442c1.146-.573 2.437.463 2.126 1.706l-.709 2.836.042-.02a.75.75 0 01.67 1.34l-.04.022c-1.147.573-2.438-.463-2.127-1.706l.71-2.836-.042.02a.75.75 0 11-.671-1.34l.041-.022zM12 9a.75.75 0 100-1.5.75.75 0 000 1.5z"
                clip-rule="evenodd"
              />
            </svg>
          </div>
        </div>
        <div class="text-center">
          <p class="text-gray-700 mb-2">您已经注册过会员请勿重复注册！</p>
          <p class="text-gray-500 text-sm">
            您的信息：{{ errorData?.您的信息 }}<br />
            您所属团长：{{ errorData?.您所属团长 }}<br />
            当前链接团长：{{ errorData?.当前链接团长 }}<br />
            <span v-if="errorData?.团长审核状态">
              团长审核状态:{{ errorData?.团长审核状态 }}
              <br />
            </span>
            注册日期：{{ errorData?.注册日期 }}
          </p>
        </div>
      </div>
    </van-dialog>

    <!-- 注册成功弹窗 -->
    <van-dialog
      v-model:show="showSuccessDialog"
      :showConfirmButton="true"
      confirmButtonText="知道了"
      class="register-dialog"
    >
      <div class="p-6">
        <div class="flex justify-center mb-4">
          <div
            class="w-12 h-12 rounded-full bg-blue-50 flex items-center justify-center"
          >
            <svg
              xmlns="http://www.w3.org/2000/svg"
              viewBox="0 0 24 24"
              fill="currentColor"
              class="w-6 h-6 text-blue-400"
            >
              <path
                fill-rule="evenodd"
                d="M2.25 12c0-5.385 4.365-9.75 9.75-9.75s9.75 4.365 9.75 9.75-4.365 9.75-9.75 9.75S2.25 17.385 2.25 12zm13.36-1.814a.75.75 0 10-1.22-.872l-3.236 4.53L9.53 12.22a.75.75 0 00-1.06 1.06l2.25 2.25a.75.75 0 001.14-.094l3.75-5.25z"
                clip-rule="evenodd"
              />
            </svg>
          </div>
        </div>
        <div class="text-center text-gray-700">
          <p>您的会员申请已提交成功，请耐心等待审核！</p>
        </div>
      </div>
    </van-dialog>

    <!-- 输入信息弹窗 -->
    <van-dialog
      v-model:show="showInputDialog"
      title="请输入信息"
      :showConfirmButton="false"
      class="register-dialog"
    >
      <div class="p-6">
        <van-field
          v-model="name"
          label="姓名"
          placeholder="请输入姓名"
          :rules="[{ required: true, message: '请输入姓名' }]"
        />
        <van-field
          v-model="phone"
          label="手机号"
          placeholder="请输入手机号"
          :rules="[{ required: true, message: '请输入手机号' }]"
        />
        <div class="mt-4 flex justify-end">
          <van-button type="primary" @click="handleInputSubmit" class="w-full">
            确认提交
          </van-button>
        </div>
      </div>
    </van-dialog>
  </div>
</template>

<style scoped>
:deep(.register-dialog) {
  .van-dialog {
    @apply rounded-xl overflow-hidden;
  }
  .van-dialog__confirm {
    @apply bg-gradient-to-r from-blue-400 to-blue-500 text-white;
  }
  .van-button__text {
    @apply text-base;
  }
}

:deep(.van-field) {
  @apply bg-transparent;

  .van-field__label {
    @apply text-gray-600 w-16 text-base;
  }

  .van-field__control {
    @apply text-gray-700;
  }
}

@keyframes float {
  0% {
    transform: translateY(0px);
  }
  50% {
    transform: translateY(-10px);
  }
  100% {
    transform: translateY(0px);
  }
}
</style>
